<template>
	<el-form size="medium" ref="form" :model="formData" :show-message="false" class="user_select_wrapper">
		<div class="user_select_table hidden-xs-only">
			<div class="head">
				<span v-for="(item, index) in columns" :key="index">{{ item.label }}</span>
			</div>
			<div class="empty" v-if="formData.forms.length === 0">暂无数据</div>
			<div v-else class="item" v-for="(item, index) in formData.forms" :key="index">
				<el-form-item v-for="(obj, idx) in columns" :key="idx" :prop="`forms.${index}.${obj.prop}`" :rules="formRules[obj.prop]">
					<template v-if="obj.mode === 'select'">
						<el-select v-model="item[obj.prop]" :placeholder="`选择${obj.label}`" @change="handleSelectChange($event, obj, index)">
							<el-option v-for="(n, i) in obj.options" :key="i" :label="n.label" :value="n.value" />
						</el-select>
					</template>
					<template v-else-if="obj.mode === 'input'">
						<el-input v-model="item[obj.prop]" :placeholder="`输入${obj.label}`"></el-input>
					</template>
					<template v-else-if="obj.mode === 'money'">
						<sw-money-input v-model="item[obj.prop]" :placeholder="`输入${obj.label}`" />
					</template>
				</el-form-item>
				<el-form-item>
					<el-button type="text" class="del" icon="el-icon-delete" @click="handleDelete(index)"></el-button>
				</el-form-item>
			</div>
		</div>
		<div class="user_select_card hidden-sm-and-up">
			<div class="empty" v-if="formData.forms.length === 0">暂无数据</div>
			<div v-else class="item" v-for="(item, index) in formData.forms" :key="index">
				<el-form-item v-for="(obj, idx) in columns" :key="idx" :prop="`forms.${index}.${obj.prop}`" :rules="formRules[obj.prop]">
					<template v-if="obj.mode === 'select'">
						<el-select v-model="item[obj.prop]" :placeholder="`选择${obj.label}`" @change="handleSelectChange($event, obj, index)">
							<el-option v-for="(n, i) in obj.options" :key="i" :label="n.label" :value="n.value" />
						</el-select>
					</template>
					<template v-else-if="obj.mode === 'input'">
						<el-input v-model="item[obj.prop]" :placeholder="`输入${obj.label}`"></el-input>
					</template>
					<template v-else-if="obj.mode === 'money'">
						<sw-money-input v-model="item[obj.prop]" :placeholder="`输入${obj.label}`" />
					</template>
				</el-form-item>
				<el-form-item>
					<el-button type="text" class="del" icon="el-icon-delete" @click="handleDelete(index)"></el-button>
				</el-form-item>
			</div>
		</div>
		<el-button type="primary" size="small" class="add" @click="handleAdded()">新增一位</el-button>
	</el-form>
</template>

<script>
import lodash from 'lodash';
import emitter from 'element-ui/src/mixins/emitter';
export default {
	mixins: [emitter],
	props: {
		value: { type: Array, default: () => [] },
		columns: { type: Array, default: () => [] }
	},
	data() {
		return {
			formData: { forms: this.value },
			formRules: {}
		};
	},
	computed: {
		validColumn() {
			return lodash.find(this.columns, { isValid: true });
		}
	},
	watch: {
		value(arr) {
			this.$set(this.formData, 'forms', arr);
		},
		'formData.forms'(arr) {
			this.$emit('input', arr);
			this.dispatch('ElFormItem', 'el.form.change', [arr]);
		}
	},
	mounted() {
		this.columns.forEach((item) => {
			let rulesData = { required: true };
			if (item.mode === 'select') {
				rulesData['trigger'] = 'change';
			} else {
				rulesData['trigger'] = 'blur';
			}
			this.$set(this.formRules, item.prop, rulesData);
		});
		if (this.validColumn) {
			let firstRulesData = [{ required: true, trigger: 'change' }];
			this.$set(this.formRules, this.validColumn.prop, firstRulesData);
		}
	},
	methods: {
		async handleAdded() {
			let isValidPass = await this.validChildForm();
			let propKeys = lodash.keyBy(this.columns, 'prop');
			let propColumns = lodash.mapValues(propKeys, (n) => '');
			if (!!isValidPass) this.formData.forms.push(propColumns);
		},

		handleDelete(index) {
			this.formData.forms.splice(index, 1);
		},

		validChildForm() {
			return new Promise(async (resolve) => {
				let forms = this.formData.forms;
				if (lodash.isEmpty(forms)) {
					resolve(true);
				} else {
					let allVailds = [];
					this.$refs['form'].clearValidate();
					for (let [index, item] of forms.entries()) {
						let propValue = item[this.validColumn.prop];
						let fields = Object.keys(item).map((n) => `forms.${index}.${n}`);
						if (!!propValue && propValue === '0') {
							allVailds.push(true);
						} else {
							let valids = [];
							await this.$refs['form'].validateField(fields, (vaild) => {
								valids.push(!vaild);
							});
							allVailds.push(!valids.includes(false));
						}
					}
					resolve(!allVailds.includes(false));
				}
			});
		},

		handleSelectChange(val, data, index) {
			if (!data.isValid) return false;
			let formRef = this.$refs['form'];
			let forms = Object.keys(this.formData.forms[index]);
			let fields = forms.map((n) => `forms.${index}.${n}`);
			formRef.clearValidate(fields);
		}
	}
};
</script>

<style lang="scss" scoped>
.user_select_wrapper {
	line-height: 1;
	.el-button.del {
		display: flex;
		font-size: 18px;
		padding: 8px;
	}
	.el-button.add {
		font-size: 14px;
		margin-top: 10px;
	}
	.el-select {
		width: 100%;
	}
}
.user_select_table {
	width: 100%;
	border: solid 1px #ebeef5;
	box-sizing: border-box;
	border-radius: 4px;
	overflow: hidden;
	.head {
		display: flex;
		padding-right: 56px;
		background-color: #f6f8fa;
		font-weight: bold;
		span {
			flex: 1;
			color: #606266;
			line-height: 1;
			font-size: 15px;
			padding: 18px 10px;
		}
	}
	.empty {
		display: flex;
		align-items: center;
		justify-content: center;
		border-top: solid 1px #ebeef5;
		font-size: 15px;
		color: #909399;
		height: 56px;
	}
	.item {
		display: flex;
		border-top: solid 1px #ebeef5;
	}
	.el-form-item {
		flex: 1;
		padding: 10px;
		overflow: hidden;
		&:last-child {
			flex: none;
			width: 36px;
			flex-shrink: 0;
		}
	}
	&:deep(.el-form-item__content) {
		line-height: 1;
	}
}
</style>
